//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Copyright 2012 Microsoft Corporation. All Rights Reserved
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.   
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

namespace Preflight.Client.Presenters
{
    using System.Web;

    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;
    using ServiceModel.Contract;

    public static class HtmlBuilder
    {
        private const string Marker = "//<<JSON>>";

        private const string ErrorMarker = "[[ERROR]]";

        public static string BuildView(PreflightCheck result)
        {
            var json = ConvertToJson(result);
            var declaration = string.Format("var cts = {0};", json);
            return Templates.Template.Replace(Marker, declaration);
        }

        public static string BuildErrorView(string message)
        {
            var messageText = HttpUtility
                                .HtmlEncode(message)
                                .Replace("\n", "<br/>");

            return Templates.ErrorTemplate.Replace(ErrorMarker, messageText);
        }

        private static string ConvertToJson(PreflightCheck result)
        {
            var settings = new JsonSerializerSettings();
            settings.Converters.Add(new StringEnumConverter());
            return JsonConvert.SerializeObject(result, settings);
        }
    }
}
